package com.itbaizhan.springsecuritydemo1.Contorller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyContorller {
    
    //获取当前用户名
    @RequestMapping("/get/getusername")
    public String getusername (){
        //获取会话对象
        SecurityContext context = SecurityContextHolder.getContext();
        //获取用户对象
        Authentication authentication = context.getAuthentication();
        //获取当前用户的登录信息
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        
        return userDetails.getUsername();
    }
}
